package com.dianrui.moonfire.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.MyApplication;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.baidumap.BaiDuUtils;
import com.dianrui.moonfire.baidumap.LocationBaiduClient;
import com.dianrui.moonfire.baidumap.RoutePlanning;
import com.dianrui.moonfire.bean.BikeModel;
import com.dianrui.moonfire.bean.BikePointModel;
import com.dianrui.moonfire.bean.CarPointBean;
import com.dianrui.moonfire.bean.StationBean;
import com.dianrui.moonfire.bean.TargetInfoModel;
import com.dianrui.moonfire.bean.WalkBabyBean;
import com.dianrui.moonfire.dialog.StartCarDialog;
import com.dianrui.moonfire.dialog.UpdateAppDialog;
import com.dianrui.moonfire.event.OpenOrClose;
import com.dianrui.moonfire.event.OpenOrCloseBaby;
import com.dianrui.moonfire.event.WalkBabyMode;
import com.dianrui.moonfire.interfaces.OnAskDialogCallBack;
import com.dianrui.moonfire.update.DownloadProssDialog;
import com.dianrui.moonfire.update.DownloadService;
import com.dianrui.moonfire.util.BadgerUtils;
import com.dianrui.moonfire.util.EventBusConstants;
import com.dianrui.moonfire.util.GlideUtil;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.util.MyOrientationListener;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.util.NoDoubleClickUtils;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.dianrui.moonfire.view.babyzxing.activity.BabyCaptureActivity;
import com.dianrui.moonfire.view.zxing.activity.CaptureActivity;
import com.dianrui.moonfire.walkbaby.WalkBabyRidingActivity;
import com.dianrui.moonfire.walkbaby.WalkBabyTipsActivity;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;

/**
 * Description:主界面
 * User: luoziyin
 * Date: 2020-8-17
 */
public class MainActivity extends BaseActivity {
    private int progress;
    private LocationBaiduClient mLocationBaiduClient;
    private TargetInfoModel mTargetInfoModel = new TargetInfoModel();
    private boolean mIsLocation = false;
    private BaiduMap mBaiduMap;
    private List<BikePointModel> mbikePointList = new ArrayList<>();
    private List<LatLng> mareaPoints = new ArrayList<>();
    private Overlay stepLine;
    private boolean isOpen;
    private String mFixedId;
    private String mTempAddress;
    private String mVehicleId;
    private String mNumbers;
    private List<BikeModel> mBikeList = new ArrayList<>();
    private List<WalkBabyBean> mWalkBabyList = new ArrayList<>();
    private long mclicktime;
    private MyOrientationListener myOrientationListener;
    private int mXDirection;
    private float mCurrentAccracy;
    private double mCurrentLantitude;
    private double mCurrentLongitude;
    private JSONArray areaJson = null;
    private List<String> imgIdArray = new ArrayList<>();
    private List<String> titlesArray = new ArrayList<>();
    private List<String> urlArray = new ArrayList<>();
    private ImageView[] imageViews;
    private ImageView imageView;
    private ViewPager viewPager;
    private LoadPageAdapter loadPageAdapter;
    private TopLoadPageAdapter topLoadPageAdapter;
    private LinearLayout viewgroup;
    private Timer timer;
    private Timer timers;
    private List<String> topimgIdArray = new ArrayList<>();
    private List<String> toptitlesArray = new ArrayList<>();
    private List<String> topurlArray = new ArrayList<>();
    private ImageView[] topimageViews;
    private ImageView topimageView;
    private boolean isMapLoaded;
    private boolean checkMapAction = false;
    private boolean checkNetAction = false;
    private boolean checkWalkBabyAction = false;
    private boolean checkCarAction = false;
    private boolean checkCenterAction = false;
    private boolean checkMapInitFinished = false;
    private int checkZoomValue = 18;
    private List<Overlay> stationMarkersList = new ArrayList<>();
    private List<Overlay> stationOverlaysList = new ArrayList<>();
    private List<Overlay> stationWalkBabyOverlaysList = new ArrayList<>();

    private List<Overlay> carMarkersList = new ArrayList<>();
    private Handler handler;
    private BitmapDescriptor bitD_NoStop;
    private BitmapDescriptor bitD_RedPack;
    private BitmapDescriptor bitD_NoCarEle;
    private BitmapDescriptor bitD_LowCarEle;
    private BitmapDescriptor bitD_HalfCarEle;
    private BitmapDescriptor bitD_FullCarEle;
    private BitmapDescriptor bitD_WalkBaby;
    private List<BitmapDescriptor> carBitDList = new ArrayList<>();
    private RoutePlanning routePlanning;

    @BindView(R.id.map)
    MapView mMap;
    @BindView(R.id.scan)
    ImageView scan;
    @BindView(R.id.walk_baby_scan)
    ImageView walkBabyScan;
    @BindView(R.id.walk_distance)
    TextView walkDistance;
    @BindView(R.id.walk_min)
    TextView walkMin;
    @BindView(R.id.parent_bike)
    LinearLayout parentBike;
    @BindView(R.id.parent_bike_point)
    LinearLayout parentBikePoint;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.show_name_address)
    TextView showNameAddress;
    @BindView(R.id.bike_number)
    TextView bikeNumber;
    @BindView(R.id.bike_power)
    TextView bikePower;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.distance)
    TextView distance;
    @BindView(R.id.min)
    TextView min;
    @BindView(R.id.see_bike_point)
    Button seeBikePoint;
    @BindView(R.id.network_ele_mode)
    Button networkEleMode;
    @BindView(R.id.ele_car_mode)
    Button eleCarMode;
    @BindView(R.id.carmode_btn)
    Button carmodeBtn;//电动车模式
    @BindView(R.id.walkbaby_btn)
    Button walkbabyBtn;//遛娃手推车
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.open_lock)
    Button openLock;
    @BindView(R.id.unread_msg)
    Button unreadMsg;
    @BindView(R.id.top_viewpager)
    ViewPager topViewpager;
    @BindView(R.id.top_close)
    Button topClose;
    @BindView(R.id.top_viewGroup)
    LinearLayout topViewGroup;
    @BindView(R.id.car_rightmode_layout)
    LinearLayout carRightmodeLayout;
    @BindView(R.id.main_carbmodebottom)
    RelativeLayout mainCarModeBottom;//底部电动车功能按钮(客服，一键定位)
    @BindView(R.id.main_walkbaybottom)
    RelativeLayout mainWalkbabybottom;//遛娃底部只有一个扫码



    @Override
    public int getContentViewId() {
        return R.layout.main;
    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        customInit(false);
        mBaiduMap = mMap.getMap();
        BaiDuUtils.initUI(mMap);
        mBaiduMap.setMyLocationEnabled(true);
        if (!MyUtil.isGpsEnable(MainActivity.this)) {
            openGpsDialog();
        }
        //将需要显示的marker初始化一遍
        loadMarkers();
        //地图加载完成回调函数
        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                checkLocationPerssions();
                initHandler();
                getUnreadNumber();
                loginAgain();
                checkUsingFirst(3);
                getAd();
                getTopAd();
                checkMapInitFinished = true;
            }
        });
        initOritationListener();
        myOrientationListener.start();
        parentBikePoint.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (stepLine != null) {
                    stepLine.remove();
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    MyUtil.initViewDownAnimation(parentBikePoint, true, false);
                }
                return true;
            }
        });
        parentBike.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (stepLine != null) {
                    stepLine.remove();
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    MyUtil.initViewDownAnimation(parentBike, true, false);
                }
                return true;
            }
        });
        View child = mMap.getChildAt(1);//将左下角百度地图logo隐藏
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                parentBike.setVisibility(View.GONE);
                parentBikePoint.setVisibility(View.GONE);
                if (stepLine != null) {
                    stepLine.remove();
                }
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {
            }
        });


        //地图移动监听事件
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
                if (i == 1) {
                    checkZoomValue = (int) mapStatus.zoom;
                    checkMapAction = true;
                } else {
                    if (checkCenterAction) {
                        checkMapAction = true;
                        checkCenterAction = false;
                        return;
                    }
                    checkMapAction = false;
                }
            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {//当手移动地图完毕时候
                if (!checkMapAction) {
                    return;
                }
                int zoom = (int) mapStatus.zoom;
                if (checkZoomValue != zoom) {
                    return;
                }
                if (parentBikePoint.getVisibility() == View.GONE && parentBike.getVisibility() == View.GONE) {
                    Constant.latLng = mapStatus.target;
                    if (Constant.MODE == 2) {
                        getWalkBabyCar(mapStatus.target);
                        return;
                    }

                    if (Constant.TYPE == 1) {
                        if (!checkNetAction) {

                            getStation(mapStatus.target);
                        }
                    } else if (Constant.TYPE == 2) {
                        if (!checkCarAction) {
                            getNearCar(mapStatus.target);
                        }

                    }
                }
            }
        });
        //marker点击事件
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getExtraInfo() != null) {
                    switch (marker.getExtraInfo().getInt("type")) {
                        case Constant.BIKE_POINT://站点模式
                            double lat = marker.getExtraInfo().getDouble("lat");
                            double lng = marker.getExtraInfo().getDouble("lng");
                            String vehicleNumber = marker.getExtraInfo().getString("vehicle_number");
                            String name = marker.getExtraInfo().getString("name");
                            String addresses = marker.getExtraInfo().getString("address");
                            MainActivity.this.mTempAddress = addresses;
                            mFixedId = String.valueOf(marker.getExtraInfo().getInt("fixed_id"));
                            double gpsDistance = Double.parseDouble(MyUtil.gpsToDistanceKM(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), lat, lng));
                            if (gpsDistance > 0.02) {
                                showBikePointInfos(gpsDistance * 1000, addresses, vehicleNumber, gpsDistance * 1000 / 0.4 / 60, name);
                                bikePointsearch(lat, lng, addresses, vehicleNumber, name);
                            } else {
                                showBikePointInfo(gpsDistance * 1000, addresses, String.valueOf(vehicleNumber), name);
                            }
                            break;

                        case Constant.BIKE_CAR_POINT://车辆模式
                            int bikecarpointId = marker.getExtraInfo().getInt("vehicle_id");//车辆id
                            double lat_ = marker.getExtraInfo().getDouble("lat");
                            double lng_ = marker.getExtraInfo().getDouble("lng");
                            String number = marker.getExtraInfo().getString("number");//车辆数量
                            String battery = marker.getExtraInfo().getString("battery");//电量
                            String journey = marker.getExtraInfo().getString("journey");//行驶多少
                            mVehicleId = String.valueOf(bikecarpointId);
                            mNumbers = number;
                            double gpsDistances = Double.parseDouble(MyUtil.gpsToDistanceKM(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), lat_, lng_));
                            if (gpsDistances > 0.02) {
                                showBikeInfo(number, battery, gpsDistances * 1000, gpsDistances * 1000 / 0.4 / 60);
                                Bikesearch(lat_, lng_, number, battery, journey);
                            } else {
                                showBikeInfo(number, battery, (int) (gpsDistances), 1);
                            }
                            break;
                        case Constant.WALK_BABY_POINT://遛娃模式
                            double blat_ = marker.getExtraInfo().getDouble("blat");
                            double blng_ = marker.getExtraInfo().getDouble("blng");//经纬度
                            String cityPath = marker.getExtraInfo().getString("city_path");//地址
                            int canNumber = marker.getExtraInfo().getInt("can_number");//可借车数量
                            int vehicleVumber = marker.getExtraInfo().getInt("vehicle_number");//可还车数量

                            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.walkbaby_ask, null);
                            TextView contentDialogAsk = view.findViewById(R.id.address_dialog_ask);
                            final TextView yesDialogAsk = view.findViewById(R.id.borrow_car_dialog_ask);
                            TextView cancelDialogAsk = view.findViewById(R.id.return_car_dialog_ask);
                            contentDialogAsk.setText(cityPath);
                            if (canNumber > 0) {
                                yesDialogAsk.setText("可借车");
                            } else {
                                yesDialogAsk.setText("不可借车");
                            }
                            if (vehicleVumber > 0) {
                                cancelDialogAsk.setText("可还车");
                            } else {
                                cancelDialogAsk.setText("不可还车");
                            }
                            final LatLng ll1 = marker.getPosition();
                            Point p1 = mBaiduMap.getProjection().toScreenLocation(ll1);
                            LatLng llInfo1 = mBaiduMap.getProjection().fromScreenLocation(p1);
                            InfoWindow mInfoWindow1 = new InfoWindow(BitmapDescriptorFactory.fromView(view), llInfo1, -130, new InfoWindow.OnInfoWindowClickListener() {
                                @Override
                                public void onInfoWindowClick() {
                                    mBaiduMap.hideInfoWindow();
                                }
                            });
                            mBaiduMap.showInfoWindow(mInfoWindow1);
                            break;
                        default:
                            break;
                    }
                }
                return true;
            }
        });
        //自动检测更新
        UpdateApp();
    }

    @SuppressLint("InflateParams")
    private void loadMarkers() {
        View view1 = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.over_nostop_point, null);
        bitD_NoStop = BitmapDescriptorFactory.fromView(view1);
        View redPackviewView = LayoutInflater.from(MainActivity.this).inflate(R.layout.over_redcarpacket_point, null);
        bitD_RedPack = BitmapDescriptorFactory.fromView(redPackviewView);
        View noCareletricView = LayoutInflater.from(MainActivity.this).inflate(R.layout.no_car_eletric, null);
        bitD_NoCarEle = BitmapDescriptorFactory.fromView(noCareletricView);

        View lowcareletricView = LayoutInflater.from(MainActivity.this).inflate(R.layout.low_car_eletric, null);
        View halfCareletricView = LayoutInflater.from(MainActivity.this).inflate(R.layout.half_car_eletric, null);
        View fullCareletricView = LayoutInflater.from(MainActivity.this).inflate(R.layout.full_car_eletric, null);

        bitD_LowCarEle = BitmapDescriptorFactory.fromView(lowcareletricView);
        bitD_HalfCarEle = BitmapDescriptorFactory.fromView(halfCareletricView);
        bitD_FullCarEle = BitmapDescriptorFactory.fromView(fullCareletricView);
    }

    @SuppressLint("InflateParams")
    private void loadWalkBabyMarkers() {
        View walkBabyview = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.walkbaby_point, null);
        bitD_WalkBaby = BitmapDescriptorFactory.fromView(walkBabyview);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMap.onDestroy();
        EventBus.getDefault().unregister(this);


        if (bitD_FullCarEle != null ) {
            bitD_FullCarEle.recycle();
            bitD_FullCarEle=null;
        }
        if (bitD_HalfCarEle != null ) {
            bitD_HalfCarEle.recycle();
            bitD_HalfCarEle=null;
        }
        if (bitD_WalkBaby != null) {
            bitD_WalkBaby.recycle();
            bitD_WalkBaby=null;
        }
        if (bitD_LowCarEle != null) {
            bitD_LowCarEle.recycle();
            bitD_LowCarEle=null;
        }
        if (bitD_NoCarEle != null) {
            bitD_NoCarEle.recycle();
            bitD_NoCarEle=null;
        }
        if (bitD_RedPack != null) {
            bitD_RedPack.recycle();
            bitD_RedPack=null;
        }
        if (bitD_NoStop != null) {
            bitD_NoStop.recycle();
            bitD_NoStop=null;
        }

        myOrientationListener.stop();
        if (mLocationBaiduClient != null) {
            mLocationBaiduClient.stop();
            mLocationBaiduClient = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        if (mWalkBabyList != null) {
            mWalkBabyList.clear();
            mWalkBabyList = null;
        }

        if (mbikePointList != null) {
            mbikePointList.clear();
            mbikePointList = null;
        }
        if (mBikeList != null) {
            mBikeList.clear();
            mBikeList = null;
        }

        if (topimgIdArray != null) {
            topimgIdArray.clear();
            topimgIdArray = null;
        }
        if (imgIdArray != null) {
            imgIdArray.clear();
            imgIdArray = null;
        }

        dismissLoadingDialog();
        if (viewPager != null) {
            viewPager.removeAllViews();
            viewPager = null;
        }
        if (topViewpager != null) {
            topViewpager.removeAllViews();
            topViewpager = null;
        }
        cancelTask();
    }


    @Override
    protected void onResume() {
        super.onResume();
        mMap.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        mMap.onPause();
    }

    //检查是否开启定位权限,有其故意关闭权限进入APP后也要有权限提醒设置
    private void checkLocationPerssions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            } else {
                startLocation();
            }
        } else {
            startLocation();
        }
    }

    // 首次运行弹出协议和隐私对话框判断
    private void setTarget() {
        SharedPreferences share = getSharedPreferences("FirstInfo", MODE_PRIVATE);
        SharedPreferences.Editor editor = share.edit();
        editor.putBoolean("isFirstIn", false);
        editor.apply();
    }

    @OnClick({R.id.scan, R.id.walk_baby_scan, R.id.carmode_btn, R.id.walkbaby_btn,
            R.id.walk_baby_location, R.id.walk_baby_custom, R.id.walk_baby_smaller, R.id.walk_baby_bigger,
            R.id.menu, R.id.message, R.id.top_close, R.id.open_lock, R.id.custom, R.id.network_ele_mode, R.id.ele_car_mode, R.id.location, R.id.bigger, R.id.see_bike_point, R.id.smaller})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.scan:
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                            checkUsing(1);
                        } else {
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 2);
                        }
                    } else {
                        checkUsing(1);
                    }
                }
                break;

            case R.id.walk_baby_scan://遛娃底部扫码
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                            checkBabyUsing(2);
                        } else {
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 2);
                        }
                    } else {
                        checkBabyUsing(2);

                    }
                }
                break;
            case R.id.menu://左上角的我的
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                    JumpActivitys(LoginActivity.class);
                } else {
                    JumpActivitys(MyActivity.class);
                }
                break;
            case R.id.message://右上角的消息
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
                    JumpActivitys(MessageActivity.class);
                }
                break;
            case R.id.carmode_btn://电动车模式
                Constant.MODE = 1;
                carmodeBtn.setBackgroundResource(R.drawable.carmode_shape);
                walkbabyBtn.setBackgroundResource(R.drawable.walkbaby_shape);
                carmodeBtn.setTextColor(getResources().getColor(R.color.black));
                walkbabyBtn.setTextColor(getResources().getColor(R.color.gray_FF959595));
                carRightmodeLayout.setVisibility(View.VISIBLE);//显示右边的站点和车辆模式
                mainCarModeBottom.setVisibility(View.VISIBLE);//共享电动车模式底部显示定位，客服
                mainWalkbabybottom.setVisibility(View.GONE);//遛娃手推车模式底部只显示扫码
                loadMarkers();
                if (Constant.MODE == 1) {
                    switch (Constant.TYPE) {
                        case 1:
                            getStation(Constant.latLng);
                            getArea(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mTargetInfoModel.getDistrict(), mTargetInfoModel.getCity(), mTargetInfoModel.getProvince());
                            break;
                        case 2:
                            getNearCar(Constant.latLng);
                            getArea(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mTargetInfoModel.getDistrict(), mTargetInfoModel.getCity(), mTargetInfoModel.getProvince());

                            break;

                        default:
                            break;
                    }

                }

                parentBike.setVisibility(View.GONE);
                parentBikePoint.setVisibility(View.GONE);
                if (stepLine != null) {
                    stepLine.remove();
                }
                break;

            case R.id.walkbaby_btn://遛娃手推车模式
                Constant.MODE = 2;
                carmodeBtn.setBackgroundResource(R.drawable.carmodeleft_shape);
                walkbabyBtn.setBackgroundResource(R.drawable.walkbabyright_shape);
                carmodeBtn.setTextColor(getResources().getColor(R.color.gray_FF959595));
                walkbabyBtn.setTextColor(getResources().getColor(R.color.black));
                carRightmodeLayout.setVisibility(View.GONE);//隐藏右边的站点和车辆模式
                mainCarModeBottom.setVisibility(View.GONE);//共享电动车模式底部显示定位，客服
                mainWalkbabybottom.setVisibility(View.VISIBLE);//遛娃手推车模式底部只显示扫码
                mBaiduMap.clear();
                loadWalkBabyMarkers();
                getWalkBabyCar(Constant.latLng);
                bitD_NoStop.recycle();
                bitD_RedPack.recycle();
                bitD_NoCarEle.recycle();
                bitD_LowCarEle.recycle();
                bitD_HalfCarEle.recycle();
                bitD_FullCarEle.recycle();
                parentBike.setVisibility(View.GONE);
                parentBikePoint.setVisibility(View.GONE);
                if (stepLine != null) {
                    stepLine.remove();
                }
                checkBabyUsingFirst(3);
                break;

            case R.id.top_close:
                topViewpager.setVisibility(View.GONE);
                topViewGroup.setVisibility(View.GONE);
                topClose.setVisibility(View.GONE);
                break;

            case R.id.see_bike_point://站点模式下跳界面借车.
                parentBikePoint.setVisibility(View.GONE);
                if (stepLine != null) {
                    stepLine.remove();
                }
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(MainActivity.this, BikePointListActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("fixed_id", mFixedId);
                    bundle.putString("address", mTempAddress);
                    bundle.putDouble("lat", mTargetInfoModel.getLatitude());
                    bundle.putDouble("lng", mTargetInfoModel.getLongitude());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                break;


            case R.id.network_ele_mode://点击电动车的站点模式
                if (Constant.latLng == null) {
                    return;
                }
                networkEleMode.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_left_choose_bg));
                eleCarMode.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_right_unchoose_bg));
                networkEleMode.setTextColor(Color.BLACK);
                eleCarMode.setTextColor(Color.BLACK);
                networkEleMode.setEnabled(false);
                eleCarMode.setEnabled(false);
                mapClear();
                clearInfo();
                Constant.TYPE = 1;
                getStation(Constant.latLng);
                break;

            case R.id.ele_car_mode://点击电动车的车辆模式
                if (Constant.latLng == null) {
                    return;
                }
                networkEleMode.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_left_unchoose_bg));
                eleCarMode.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_right_choose_bg));
                networkEleMode.setTextColor(Color.BLACK);
                eleCarMode.setTextColor(Color.BLACK);
                networkEleMode.setEnabled(false);
                eleCarMode.setEnabled(false);
                mapClear();
                clearInfo();
                Constant.TYPE = 2;
                getNearCar(Constant.latLng);
                break;

            case R.id.open_lock:
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else if (StringUtils.isEmpty(mVehicleId)) {
                    ToastUtil.showToast(getString(R.string.car_info_error));
                } else {
                    StartCarDialog.createStartCarDialog(MainActivity.this, getString(R.string.start_car_txt), new OnAskDialogCallBack() {
                        @Override
                        public void onokey(Dialog dialog) {
                            dialog.dismiss();
                            parentBike.setVisibility(View.GONE);
                            if (stepLine != null) {
                                stepLine.remove();
                            }
                            remoteDetection(mVehicleId, mNumbers);
                        }

                        @Override
                        public void onCancel(Dialog dialog) {
                            dialog.dismiss();
                        }
                    });

                }
                break;
            case R.id.bigger://放大
                BaiDuUtils.setMapStatus(mMap, BaiDuUtils.getZoom(mMap) + 1);
                break;
            case R.id.smaller://缩小
                BaiDuUtils.setMapStatus(mMap, BaiDuUtils.getZoom(mMap) - 1);
                break;
            case R.id.location:
                if (mTargetInfoModel.getLatitude() == Constant.NO_LATITUDE && mTargetInfoModel.getLongitude() == Constant.NO_LONGITUDE) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                BaiDuUtils.locationTarget(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mMap, BaiDuUtils.getZoom(mMap));
                            }
                        }, 800);
                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 3);
                    }
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            BaiDuUtils.locationTarget(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mMap, BaiDuUtils.getZoom(mMap));
                        }
                    }, 800);
                }
                break;
            case R.id.walk_baby_custom://客服
                JumpActivitys(CustomerWebViewActivity.class);
                break;

            case R.id.walk_baby_bigger://放大
                BaiDuUtils.setMapStatus(mMap, BaiDuUtils.getZoom(mMap) + 1);
                break;
            case R.id.walk_baby_smaller://缩小
                BaiDuUtils.setMapStatus(mMap, BaiDuUtils.getZoom(mMap) - 1);
                break;
            case R.id.walk_baby_location://
                if (mTargetInfoModel.getLatitude() == Constant.NO_LATITUDE && mTargetInfoModel.getLongitude() == Constant.NO_LONGITUDE) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                BaiDuUtils.locationTarget(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mMap, BaiDuUtils.getZoom(mMap));
                            }
                        }, 800);
                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 3);
                    }
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            BaiDuUtils.locationTarget(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mMap, BaiDuUtils.getZoom(mMap));
                        }
                    }, 800);
                }
                break;
            case R.id.custom://客服
                JumpActivitys(CustomerWebViewActivity.class);
                break;
            default:
                break;
        }

    }


    // 开始定位
    private void startLocation() {
        mLocationBaiduClient = new LocationBaiduClient(getApplicationContext(), 2000, false, BaiDuUtils.initLocationListerer(mTargetInfoModel, new BaiDuUtils.OnLocationCallBack() {
            @Override
            public void onLocationSuccess(TargetInfoModel mTargetInfoModel) {
                MainActivity.this.mTargetInfoModel = mTargetInfoModel;
                if (!mIsLocation) {
                    Constant.TYPE = 1;
                    SPUtils.getInstance().put("userLat", mTargetInfoModel.getLatitude() + "");
                    SPUtils.getInstance().put("userLng", mTargetInfoModel.getLongitude() + "");
                    Constant.latLng = new LatLng(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude());
                    BaiDuUtils.locationTarget(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mMap, 18f);
                    getStation(new LatLng(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude()));
                    getArea(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mTargetInfoModel.getDistrict(), mTargetInfoModel.getCity(), mTargetInfoModel.getProvince());
                    mIsLocation = true;
                }

                mCurrentLantitude = mTargetInfoModel.getLatitude();
                mCurrentLongitude = mTargetInfoModel.getLongitude();
                mCurrentAccracy = mTargetInfoModel.getAccuracy();
                BaiDuUtils.setMyLocationData(MyLocationConfiguration.LocationMode.NORMAL,
                        true,
                        BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked),
                        R.color.main_color,
                        R.color.main_color,
                        mTargetInfoModel.getAccuracy(),
                        mTargetInfoModel.getLatitude(),
                        mTargetInfoModel.getLongitude(), mTargetInfoModel.getGetBearing(), mMap);
            }

            @Override
            public void onLocationFail(String errorInfo) {
            }
        }));
        mLocationBaiduClient.start();

    }

    //初始化方向传感器
    private void initOritationListener() {
        myOrientationListener = new MyOrientationListener(getApplicationContext());
        myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
            @Override
            public void onOrientationChanged(float x) {
                mXDirection = (int) x;
                // 构造定位数据
                MyLocationData locData = new MyLocationData.Builder().accuracy(mCurrentAccracy).direction(mXDirection).latitude(mCurrentLantitude).longitude(mCurrentLongitude).build();
                mMap.getMap().setMyLocationData(locData);
                BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
                MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker);
                mMap.getMap().setMyLocationConfiguration(config);
            }
        });
    }


    //获取广告
    @SuppressLint("InflateParams")
    private void getAd() {
        if (null != imgIdArray && imgIdArray.size() > 0) {
            imgIdArray.clear();
        }
        if (null != titlesArray && titlesArray.size() > 0) {
            titlesArray.clear();
        }
        if (null != urlArray && urlArray.size() > 0) {
            urlArray.clear();
        }
        JsonObject jsonObject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
            jsonObject.addProperty("area_id", SPUtils.getInstance().getString("area_id"));
        } else {
            jsonObject.addProperty("area_id", "0");
        }
        jsonObject.addProperty("type", "2");
        try {
            XHttpRequest.getInstance().postNormalRequests(Url.ADV, jsonObject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.getString(Constant.STATUS))) {
                                    JSONArray jsonArray = jsonObject.optJSONArray("data");
                                    if (jsonArray.length() > 0) {
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject content = new JSONObject(jsonArray.opt(i).toString());
                                            imgIdArray.add(content.optString("picture"));
                                            titlesArray.add(content.optString("title"));
                                            urlArray.add(content.optString("link_url"));
                                        }
                                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.RcDialog);
                                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.ad_dialog, null);
                                        final AlertDialog dialog = builder.create();
                                        dialog.setView(view);
                                        dialog.show();
                                        viewPager = view.findViewById(R.id.viewpager);
                                        viewgroup = view.findViewById(R.id.viewGroup);
                                        if (loadPageAdapter == null) {
                                            loadPageAdapter = new LoadPageAdapter();
                                            viewPager.setAdapter(loadPageAdapter);
                                        } else {
                                            loadPageAdapter.notifyDataSetChanged();
                                        }
                                        viewPager.addOnPageChangeListener(new BannerListener());
                                        if (imgIdArray.size() == 1) {
                                            viewgroup.setVisibility(View.GONE);
                                        } else {
                                            //有多少个界面就new多长的数组
                                            imageViews = new ImageView[imgIdArray.size()];
                                            for (int i = 0; i < imageViews.length; i++) {
                                                //new新的ImageView控件
                                                imageView = new ImageView(MainActivity.this);
                                                //设置控件的宽高
                                                imageView.setLayoutParams(new ViewGroup.LayoutParams(10, 10));
                                                //设置控件的padding属性
                                                imageView.setPadding(5, 0, 5, 0);
                                                imageViews[i] = imageView;
                                                //初始化第一个page页面的图片的原点为选中状态
                                                if (i == 0) {
                                                    //表示当前图片
                                                    imageViews[i].setBackgroundResource(R.drawable.green_dot);
                                                } else {
                                                    imageViews[i].setBackgroundResource(R.drawable.gray_dot);
                                                }
                                                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                                                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                                                layoutParams.leftMargin = 5;
                                                layoutParams.rightMargin = 10;
                                                layoutParams.bottomMargin = 15;
                                                layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                                                // 将imageviews添加到小圆点视图组
                                                viewgroup.addView(imageViews[i], layoutParams);
                                            }
                                        }

                                        setViewPagerTime();
                                        Button closeTxt = view.findViewById(R.id.close);
                                        closeTxt.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                dialog.cancel();
                                                if (viewPager != null) {
                                                    viewPager.removeAllViews();
                                                    viewPager.removeOnPageChangeListener(null);
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {

                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    //获取顶部广告
    private void getTopAd() {
        if (topimgIdArray != null && topimgIdArray.size() > 0) {
            imgIdArray.clear();
        }
        if (toptitlesArray != null && toptitlesArray.size() > 0) {
            toptitlesArray.clear();
        }
        if (topurlArray != null && topurlArray.size() > 0) {
            topurlArray.clear();
        }

        JsonObject jsonObject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
            jsonObject.addProperty("area_id", SPUtils.getInstance().getString("area_id"));
        }
        jsonObject.addProperty("type", "3");
        try {
            XHttpRequest.getInstance().postNormalRequests(Url.ADV, jsonObject.toString(), new XHttpRequest.XCallBack() {

                @Override
                public void onResponse(String result) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.getString(Constant.STATUS))) {
                                    JSONArray jsonArray = jsonObject.optJSONArray("data");
                                    if (jsonArray.length() > 0) {
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject content = new JSONObject(jsonArray.opt(i).toString());
                                            topimgIdArray.add(content.optString("picture"));
                                            toptitlesArray.add(content.optString("title"));
                                            topurlArray.add(content.optString("link_url"));
                                        }
                                        if (topLoadPageAdapter == null) {
                                            topLoadPageAdapter = new TopLoadPageAdapter();
                                            topViewpager.setAdapter(topLoadPageAdapter);
                                        } else {
                                            topLoadPageAdapter.notifyDataSetChanged();
                                        }
                                        topViewpager.addOnPageChangeListener(new TopBannerListener());
                                        if (topimgIdArray.size() == 1) {
                                            topViewGroup.setVisibility(View.GONE);
                                        } else {
                                            //有多少个界面就new多长的数组
                                            topimageViews = new ImageView[topimgIdArray.size()];
                                            for (int i = 0; i < topimageViews.length; i++) {
                                                //new新的ImageView控件
                                                topimageView = new ImageView(MainActivity.this);
                                                //设置控件的宽高
                                                topimageView.setLayoutParams(new ViewGroup.LayoutParams(10, 10));
                                                //设置控件的padding属性
                                                topimageView.setPadding(5, 0, 5, 0);
                                                topimageViews[i] = topimageView;
                                                //初始化第一个page页面的图片的原点为选中状态
                                                if (i == 0) {
                                                    //表示当前图片
                                                    topimageViews[i].setBackgroundResource(R.drawable.green_dot);
                                                } else {
                                                    topimageViews[i].setBackgroundResource(R.drawable.gray_dot);
                                                }
                                                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                                                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                                                layoutParams.leftMargin = 5;
                                                layoutParams.rightMargin = 10;
                                                layoutParams.bottomMargin = 15;
                                                layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                                                // 将imageviews添加到小圆点视图组
                                                topViewGroup.addView(topimageViews[i], layoutParams);
                                                topViewGroup.setVisibility(View.VISIBLE);
                                            }

                                        }
                                        setTopViewPagerTime();
                                        topClose.setVisibility(View.VISIBLE);
                                        topViewpager.setVisibility(View.VISIBLE);
                                        topViewGroup.setVisibility(View.VISIBLE);

                                    } else {
                                        topViewpager.setVisibility(View.GONE);
                                        topViewGroup.setVisibility(View.GONE);
                                        topClose.setVisibility(View.GONE);
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        topViewpager.setVisibility(View.GONE);
                        topViewGroup.setVisibility(View.GONE);
                        topClose.setVisibility(View.GONE);
                    }
                }

                @Override
                public void failedRequest(String result) {

                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    private void setTopViewPagerTime() {
        timers = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                topViewpager.setCurrentItem(topViewpager.getCurrentItem() + 1);
            }
        };
        timers.schedule(task, 0, 2000);
    }

    private void setViewPagerTime() {
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            }
        };
        timer.schedule(task, 0, 2000);
    }

    //清除信息，如之前画的规划路线
    private void clearInfo() {
        if (stepLine != null) {
            stepLine.remove();
        }
        parentBikePoint.setVisibility(View.GONE);
        parentBike.setVisibility(View.GONE);
    }

    class TopLoadPageAdapter extends PagerAdapter {//顶部广告的适配器

        @Override
        public int getCount() {
            if (topimgIdArray == null) {
                return 0;
            }
            if (topimgIdArray.size() == 1) {
                return topimgIdArray.size();
            } else {
                return Integer.MAX_VALUE;//图片有多少张就有多少
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            ImageView imageView = new ImageView(MainActivity.this);
            if (topimgIdArray.size() > 0) {
                final int newPostion = position % topimgIdArray.size();
                GlideUtil.loadImageView(getApplicationContext(), topimgIdArray.get(newPostion), imageView);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (topimgIdArray.size() == 1) {
                        } else {
                            startActivity(new Intent(MainActivity.this, AdWebViewActivity.class)
                                    .putExtra("titles", toptitlesArray.get(newPostion))
                                    .putExtra("url", topurlArray.get(newPostion)));
                        }
                    }
                });
            }
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    class LoadPageAdapter extends PagerAdapter {//主页弹窗广告适配器

        @Override
        public int getCount() {
            if (imgIdArray == null) {
                return 0;
            }
            if (imgIdArray.size() == 1) {
                return imgIdArray.size();//如果是一张图就无需轮播
            } else {
                return Integer.MAX_VALUE;//无限轮播
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            ImageView imageView = new ImageView(MainActivity.this);
            if (imgIdArray.size() > 0) {
                final int newPostion = position % imgIdArray.size();
                GlideUtil.loadImageView(getApplicationContext(), imgIdArray.get(newPostion), imageView);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (imgIdArray.size() == 1) {
                        } else {
                            startActivity(new Intent(MainActivity.this, AdWebViewActivity.class)
                                    .putExtra("titles", titlesArray.get(newPostion))
                                    .putExtra("url", urlArray.get(newPostion)));
                        }
                    }
                });
            }
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    class BannerListener implements ViewPager.OnPageChangeListener {


        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            if (imageViews.length > 0) {
                final int newPostion = position % imgIdArray.size();
                for (int i = 0; i < imageViews.length; i++) {
                    imageViews[newPostion].setBackgroundResource(R.drawable.green_dot);
                    if (newPostion != i) {
                        imageViews[i].setBackgroundResource(R.drawable.gray_dot);
                    }
                }

            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }

    class TopBannerListener implements ViewPager.OnPageChangeListener {


        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            if (topimageViews.length > 0) {
                final int newPostion = position % topimgIdArray.size();
                for (int i = 0; i < topimageViews.length; i++) {
                    topimageViews[newPostion].setBackgroundResource(R.drawable.green_dot);
                    if (newPostion != i) {
                        topimageViews[i].setBackgroundResource(R.drawable.gray_dot);
                    }
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }


    //电子围栏
    public void getArea(double latitude, double longitude, String district, String city, String province) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("gps", longitude + "," + latitude);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        jsonObject.addProperty("district", district);
        jsonObject.addProperty("city", city);
        jsonObject.addProperty("province", province);
        try {
            XHttpRequest.getInstance().postRequests(Url.AREA, jsonObject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) throws JSONException {
                    if (!StringUtils.isEmpty(result)) {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString(Constant.STATUS))) {
                                if (mareaPoints != null && mareaPoints.size() > 0) {
                                    mareaPoints.clear();
                                }
                                JSONArray jsonArray3 = jsonObject.optJSONArray("data");
                                if (jsonArray3.length() > 0) {
                                    JSONObject jsonObject1 = jsonArray3.optJSONObject(0);
                                    String areaIds = jsonObject1.optString("area_id");
                                    SPUtils.getInstance().put("area_id", areaIds,true);
                                    areaJson = jsonObject1.optJSONArray("bfixed_path");
                                    SPUtils.getInstance().put("area_data", String.valueOf(areaJson),true);
                                    drawArea();
                                } else {
                                    SPUtils.getInstance().put("area_id", "0");
                                }
                            }
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
        }


    }

    public void drawArea() {
        JSONArray jsonArray1 = areaJson;
        if (jsonArray1.length() > 0) {
            for (int j = 0; j < jsonArray1.length(); j++) {
                if (j == jsonArray1.length()) {
                    JSONObject jsonObject2 = jsonArray1.optJSONObject(0);
                    mareaPoints.add(new LatLng(jsonObject2.optDouble("lat"), jsonObject2.optDouble("lng")));
                } else {
                    JSONObject jsonObject2 = jsonArray1.optJSONObject(j);
                    mareaPoints.add(new LatLng(jsonObject2.optDouble("lat"), jsonObject2.optDouble("lng")));
                }
            }
            if (mareaPoints.size() < 2) {
                return;
            }

            if (mareaPoints.size() > 0) {
                List<BitmapDescriptor> picList = new ArrayList<>();
                picList.add(BitmapDescriptorFactory.fromResource(R.drawable.area_img));

                List<Integer> textureIndexs = new ArrayList<>();
                textureIndexs.add(0);
                OverlayOptions ooPolyline11 = new PolylineOptions().width(14).points(mareaPoints).dottedLine(true).textureIndex(textureIndexs).customTextureList(picList);
                mBaiduMap.addOverlay(ooPolyline11);
            }
        }
    }

    //获取网点
    @SuppressLint("InflateParams")
    private void getStation(LatLng target) {
        checkNetAction = true;
        JsonObject stationJsonobject = new JsonObject();
        if (target != null) {
            stationJsonobject.addProperty("gps", target.longitude + "," + target.latitude);
        } else {
            stationJsonobject.addProperty("gps", SPUtils.getInstance().getString("userLat") + "," + SPUtils.getInstance().getString("userLng"));
        }
        stationJsonobject.addProperty("type_id", "2");
        try {
            XHttpRequest.getInstance().postRequests(Url.GETNETWORK, stationJsonobject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) {
                    checkNetAction = false;
                    if (!StringUtils.isEmpty(result)) {
                        networkEleMode.setEnabled(true);
                        eleCarMode.setEnabled(true);
                        Message message = new Message();
                        if (isFinishing()) {
                            return;
                        }
                        String status = JsonUtils.getJsonStr(result, Constant.STATUS);
                        if (Constant.DATASUCCESS.equals(status)) {
                            mapClear();
                            if (mbikePointList.size() > 0) {
                                mbikePointList.clear();
                            }
                            String data = JsonUtils.getJsonStr(result, "data");
                            List<CarPointBean> carPointBeanList = JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<CarPointBean>>() {}.getType());
                            if (carPointBeanList == null || carPointBeanList.isEmpty()) {
                                return;
                            }
                            List<OverlayOptions> overlaysList = new ArrayList<>();
                            for (int i = 0; i < carPointBeanList.size(); i++) {
                                CarPointBean carPointBean = carPointBeanList.get(i);
                                BikePointModel bikePointModel = StationBean.CarToBikePoint(carPointBean);
                                mbikePointList.add(bikePointModel);
                                if ("1".equals(carPointBean.fixed_type)) {
                                    if (carPointBean.bfixed_path == null || carPointBean.bfixed_path.isEmpty()) {
                                        return;
                                    }
                                    List<LatLng> points = new ArrayList<>();
                                    for (int j = 0; j < carPointBean.bfixed_path.size(); j++) {
                                        points.add(new LatLng(carPointBean.bfixed_path.get(j).lat, carPointBean.bfixed_path.get(j).lng));
                                    }
                                    points.add(new LatLng(carPointBean.bfixed_path.get(0).lat, carPointBean.bfixed_path.get(0).lng));
                                    if (points.size() < 2) {
                                        return;
                                    }

                                    List<LatLng> overLatlngList = new ArrayList<>(points);

                                    //is_forbid是1禁停区域
                                    if ("1".equals(carPointBean.is_forbid)) {
                                        OverlayOptions ooPolyline = new PolylineOptions().width(4).color(Color.RED).points(overLatlngList).dottedLine(true);
                                        overlaysList.add(ooPolyline);

                                        OverlayOptions ooPolygon1 = new PolygonOptions().points(overLatlngList).fillColor(Color.argb(46, 255, 0, 0));
                                        overlaysList.add(ooPolygon1);

                                        OverlayOptions markerOptions = new MarkerOptions().position(new LatLng(mbikePointList.get(i).blat, mbikePointList.get(i).blng)).icon(bitD_NoStop);
                                        overlaysList.add(markerOptions);

                                    } else {
                                        OverlayOptions overlayOptions = new PolylineOptions().width(4).color(getResources().getColor(R.color.main_color)).points(overLatlngList).dottedLine(true);
                                        overlaysList.add(overlayOptions);
                                        //填充
                                        OverlayOptions ooPolygon = new PolygonOptions().points(overLatlngList).fillColor(Color.argb(46, 244, 225, 5));
                                        overlaysList.add(ooPolygon);

                                        Bundle bundle = new Bundle();
                                        bundle.putInt("type", Constant.BIKE_POINT);
                                        bundle.putInt("fixed_id", mbikePointList.get(i).fixed_id);
                                        bundle.putString("name", mbikePointList.get(i).name);
                                        bundle.putString("slogan", mbikePointList.get(i).slogan);
                                        bundle.putDouble("lat", mbikePointList.get(i).blat);
                                        bundle.putDouble("lng", mbikePointList.get(i).blng);
                                        bundle.putString("vehicle_number", mbikePointList.get(i).vehicle_number);
                                        bundle.putString("address", mbikePointList.get(i).city_path);

                                        View view = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.over_elecar_point, null);
                                        TextView markernum = view.findViewById(R.id.station_number_blue_dot);
                                        int number = Integer.parseInt(mbikePointList.get(i).vehicle_number);
                                        if (number > 9) {
                                            String showMarkernumplus = 9 + "+" + "";
                                            markernum.setText(showMarkernumplus);
                                        } else {
                                            String showVehicleNumber = mbikePointList.get(i).vehicle_number + "";
                                            markernum.setText(showVehicleNumber);
                                        }
                                        BitmapDescriptor BitDCar = BitmapDescriptorFactory.fromView(view);
                                        OverlayOptions markerOptions = new MarkerOptions().position(new LatLng(mbikePointList.get(i).blat, mbikePointList.get(i).blng)).icon(BitDCar).extraInfo(bundle);
                                        carBitDList.add(BitDCar);
                                        overlaysList.add(markerOptions);

                                    }
                                } else if ("0".equals(carPointBean.fixed_type)) {

                                    if ("1".equals(carPointBean.is_forbid)) {
                                        int networkRange = Integer.parseInt(carPointBean.network_range);
                                        LatLng center = new LatLng(mbikePointList.get(i).blat, mbikePointList.get(i).blng);
                                        CircleOptions circleOptions = new CircleOptions();
                                        circleOptions.center(center);//设置圆心坐标
                                        circleOptions.fillColor(Color.argb(36, 244, 225, 5));//圆的填充颜色
                                        circleOptions.radius(networkRange);//设置半径
                                        overlaysList.add(circleOptions);

                                        OverlayOptions markerOptions = new MarkerOptions().position(new LatLng(mbikePointList.get(i).blat, mbikePointList.get(i).blng)).icon(bitD_NoStop);
                                        overlaysList.add(markerOptions);
                                    }else {
                                        int networkRange = Integer.parseInt(carPointBean.network_range);
                                        LatLng center = new LatLng(mbikePointList.get(i).blat, mbikePointList.get(i).blng);
                                        CircleOptions circleOptions = new CircleOptions();
                                        circleOptions.center(center);//设置圆心坐标
                                        circleOptions.fillColor(Color.argb(36, 244, 225, 5));//圆的填充颜色
                                        circleOptions.radius(networkRange);//设置半径
                                        overlaysList.add(circleOptions);
                                    }
                                }
                            }
                            if (overlaysList.size() > 0) {
                                stationOverlaysList.addAll(mBaiduMap.addOverlays(overlaysList));
                            }
                            message.what = 1;
                        }
                        handler.sendMessage(message);
                    } else {
                        networkEleMode.setEnabled(true);
                        eleCarMode.setEnabled(true);
                        checkNetAction = false;
                    }
                }

                @Override
                public void failedRequest(String result) {
                    ToastUtil.showToast(getString(R.string.net_error));
                    mapClear();
                    networkEleMode.setEnabled(true);
                    eleCarMode.setEnabled(true);
                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }


    //附近的电动车
    @SuppressLint("InflateParams")
    public void getNearCar(LatLng target) {
        checkCarAction = false;
        JsonObject nearCarJsonObject = new JsonObject();
        if (target != null) {
            nearCarJsonObject.addProperty("gps", target.longitude + "," + target.latitude);
        } else {
            nearCarJsonObject.addProperty("gps", SPUtils.getInstance().getString("userLat") + "," + SPUtils.getInstance().getString("userLng"));
        }
        nearCarJsonObject.addProperty("type_id", "2");
        try {
            XHttpRequest.getInstance().postRequests(Url.GETNEARBY_BIKE, nearCarJsonObject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) throws JSONException {
                    checkCarAction = false;
                    if (!StringUtils.isEmpty(result)) {
                        networkEleMode.setEnabled(true);
                        eleCarMode.setEnabled(true);
                        Message message = new Message();
                        if (isFinishing()) {
                            return;
                        }
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString(Constant.STATUS))) {
                                mapClear();
                                if (null != mBikeList && mBikeList.size() > 0) {
                                    mBikeList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        BikeModel bikeModel = new BikeModel();
                                        bikeModel.vehicle_id = jsonArray.optJSONObject(i).optInt("vehicle_id");
                                        bikeModel.number = jsonArray.optJSONObject(i).optString("number");
                                        bikeModel.remark = jsonArray.optJSONObject(i).optString("remark");
                                        bikeModel.lat = jsonArray.optJSONObject(i).optDouble("blat");
                                        bikeModel.lng = jsonArray.optJSONObject(i).optDouble("blng");
                                        bikeModel.device = jsonArray.optJSONObject(i).optString("device");
                                        bikeModel.distance = jsonArray.optJSONObject(i).optDouble("distance");
                                        bikeModel.red_packet = jsonArray.optJSONObject(i).optString("red_packet");
                                        bikeModel.battery = jsonArray.optJSONObject(i).optString("battery");
                                        bikeModel.journey = jsonArray.optJSONObject(i).optString("journey");
                                        bikeModel.batterys = jsonArray.optJSONObject(i).optInt("battery");
                                        mBikeList.add(bikeModel);

                                    }
                                    message.what = 2;
                                }
                            } else {
                                checkCarAction = false;
                            }

                        }
                        handler.sendMessage(message);
                    } else {
                        networkEleMode.setEnabled(true);
                        eleCarMode.setEnabled(true);
                        checkCarAction = false;
                    }
                }

                @Override
                public void failedRequest(String result) {
                    ToastUtil.showToast(getString(R.string.net_error));
                    mapClear();
                    networkEleMode.setEnabled(true);
                    eleCarMode.setEnabled(true);
                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    //获取遛娃手推车的marker
    private void getWalkBabyCar(LatLng latLng) {
        JsonObject walkBabyJsonObject = new JsonObject();
        if (latLng != null) {
            walkBabyJsonObject.addProperty("gps", latLng.longitude + "," + latLng.latitude);
        } else {
            walkBabyJsonObject.addProperty("gps", SPUtils.getInstance().getString("userLat") + "," + SPUtils.getInstance().getString("userLng"));
        }
        try {
            XHttpRequest.getInstance().postRequests(Url.BABYPOINT, walkBabyJsonObject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) throws JSONException {
                    if (!StringUtils.isEmpty(result)) {
                        if (isFinishing()) {
                            return;
                        }
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString(Constant.STATUS))) {

                                if (mWalkBabyList.size() > 0) {
                                    mWalkBabyList.clear();
                                }
                                List<OverlayOptions> overlaysList = new ArrayList<>();
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        WalkBabyBean walkBabyBean = new WalkBabyBean();
                                        walkBabyBean.blat = jsonArray.optJSONObject(i).optDouble("blat");
                                        walkBabyBean.blng = jsonArray.optJSONObject(i).optDouble("blng");
                                        walkBabyBean.city_path = jsonArray.optJSONObject(i).optString("city_path");
                                        walkBabyBean.can_number = jsonArray.optJSONObject(i).optInt("can_number");
                                        walkBabyBean.network_range = jsonArray.optJSONObject(i).optInt("network_range");
                                        walkBabyBean.vehicle_number = jsonArray.optJSONObject(i).optInt("vehicle_number");
                                        mWalkBabyList.add(walkBabyBean);

                                        int networkRange = jsonArray.optJSONObject(i).optInt("network_range");
                                        LatLng center = new LatLng(mWalkBabyList.get(i).blat, mWalkBabyList.get(i).blng);
                                        CircleOptions circleOptions = new CircleOptions();
                                        circleOptions.center(center);//设置圆心坐标
                                        circleOptions.fillColor(Color.argb(36, 244, 225, 5));//圆的填充颜色
                                        circleOptions.radius(networkRange);//设置半径
                                        overlaysList.add(circleOptions);

                                        Bundle bundle = new Bundle();
                                        bundle.putInt("type", Constant.WALK_BABY_POINT);
                                        bundle.putInt("vehicle_number", mWalkBabyList.get(i).vehicle_number);
                                        bundle.putInt("can_number", mWalkBabyList.get(i).can_number);
                                        bundle.putString("city_path", mWalkBabyList.get(i).city_path);
                                        bundle.putDouble("blat", mWalkBabyList.get(i).blat);
                                        bundle.putDouble("blng", mWalkBabyList.get(i).blng);

                                        MarkerOptions markerOptions1 = new MarkerOptions();
                                        markerOptions1.position(new LatLng(mWalkBabyList.get(i).blat, mWalkBabyList.get(i).blng)).icon(bitD_WalkBaby).zIndex(10);
                                        markerOptions1.extraInfo(bundle);
                                        overlaysList.add(markerOptions1);
                                    }

                                    if (overlaysList.size() > 0) {
                                        stationWalkBabyOverlaysList.addAll(mBaiduMap.addOverlays(overlaysList));
                                    }

                                }
                            } else {
                                checkWalkBabyAction = false;
                            }

                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    ToastUtil.showToast(getString(R.string.net_error));
                    mapClear();
                    networkEleMode.setEnabled(true);
                    eleCarMode.setEnabled(true);
                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

    //耗时操作扔handler
    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 2:
                        List<OverlayOptions> lists = new ArrayList<>();
                        for (int i = 0; i < mBikeList.size(); i++) {
                            Bundle bundle = new Bundle();
                            bundle.putInt("type", Constant.BIKE_CAR_POINT);
                            bundle.putInt("vehicle_id", mBikeList.get(i).vehicle_id);
                            bundle.putDouble("lat", mBikeList.get(i).lat);
                            bundle.putDouble("lng", mBikeList.get(i).lng);
                            bundle.putString("device", mBikeList.get(i).device);
                            bundle.putString("red_packet", mBikeList.get(i).red_packet);
                            bundle.putString("number", mBikeList.get(i).number);
                            bundle.putString("battery", mBikeList.get(i).battery);
                            bundle.putString("journey", mBikeList.get(i).journey);
                            int batterys = mBikeList.get(i).batterys;
                            String red_packet = mBikeList.get(i).red_packet;

                            if (red_packet.equals("1")) {
                                MarkerOptions markerOptions1 = new MarkerOptions();
                                markerOptions1.position(new LatLng(mBikeList.get(i).lat, mBikeList.get(i).lng)).icon(bitD_RedPack).zIndex(10);
                                markerOptions1.extraInfo(bundle);
                                lists.add(markerOptions1);
                            } else {
                                if (batterys <= 30) {
                                    MarkerOptions markerOptions = new MarkerOptions();
                                    markerOptions.position(new LatLng(mBikeList.get(i).lat, mBikeList.get(i).lng)).icon(bitD_NoCarEle).zIndex(10);
                                    markerOptions.extraInfo(bundle);
                                    lists.add(markerOptions);
                                } else if (batterys > 30 && batterys < 50) {
                                    MarkerOptions markerOptions = new MarkerOptions();
                                    markerOptions.position(new LatLng(mBikeList.get(i).lat, mBikeList.get(i).lng)).icon(bitD_LowCarEle).zIndex(10);
                                    markerOptions.extraInfo(bundle);
                                    lists.add(markerOptions);

                                } else if (batterys >= 50 && batterys < 80) {
                                    MarkerOptions markerOptions = new MarkerOptions();
                                    markerOptions.position(new LatLng(mBikeList.get(i).lat, mBikeList.get(i).lng)).icon(bitD_HalfCarEle).zIndex(10);
                                    markerOptions.extraInfo(bundle);
                                    lists.add(markerOptions);

                                } else if (batterys >= 80) {
                                    MarkerOptions markerOptions = new MarkerOptions();
                                    markerOptions.position(new LatLng(mBikeList.get(i).lat, mBikeList.get(i).lng)).icon(bitD_FullCarEle).zIndex(10);
                                    markerOptions.extraInfo(bundle);
                                    lists.add(markerOptions);
                                }
                            }
                        }
                        if (lists.size() > 0) {
                            mapClear();
                            carMarkersList.addAll(mMap.getMap().addOverlays(lists));

                        }
                        break;
                    default:
                        break;
                }

            }
        };
    }

    //打开GPS对话框
    @SuppressLint("InflateParams")
    private void openGpsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.RcDialog);
        final View view2 = LayoutInflater.from(MainActivity.this).inflate(R.layout.open_gps_dialog, null);
        final AlertDialog pausedialog = builder.create();
        pausedialog.setView(view2);
        pausedialog.setCanceledOnTouchOutside(false);
        pausedialog.show();
        final Button yes = view2.findViewById(R.id.yes);

        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pausedialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 6);
            }
        });
    }

    //再次登录
    public void loginAgain() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        jsonObject.addProperty("device_number", MyUtil.getUniqueId(MainActivity.this));//设备号
        jsonObject.addProperty("type", "1");
        jsonObject.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());
        jsonObject.addProperty("app_version", MyUtil.getAppInfo(MainActivity.this));
        jsonObject.addProperty("device_version", MyUtil.getOS());
        XHttpRequest.getInstance().postRequests(Url.LOGIN_AGAIN, jsonObject.toString(), new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) throws JSONException {
                if (!StringUtils.isEmpty(result)) {
                    if (isFinishing()) {
                        return;
                    }
                    final JSONObject jsonObject = new JSONObject(result);
                    if (null != jsonObject) {
                        if (Constant.DATASUCCESS.equals(jsonObject.optString(Constant.STATUS))) {
                            SPUtils.getInstance().put(Constant.MEMBER_ID, jsonObject.optJSONObject("data").optString("member_id"),true);//用户ID，非常重要，必须获取
                            SPUtils.getInstance().put(Constant.ACCOUNT, jsonObject.optJSONObject("data").optString("account"),true);//账户
                            SPUtils.getInstance().put(Constant.EMAIL, jsonObject.optJSONObject("data").optString("email"),true);//电子邮件
                            SPUtils.getInstance().put(Constant.MOBILE, jsonObject.optJSONObject("data").optString("mobile"),true);//手机
                            SPUtils.getInstance().put(Constant.NICKENAME, jsonObject.optJSONObject("data").optString("nickname"),true);//昵称
                            SPUtils.getInstance().put(Constant.SCANURL, jsonObject.optJSONObject("data").optString("scan_url"),true);
                            SPUtils.getInstance().put(Constant.NAME, jsonObject.optJSONObject("data").optString("name"),true);//用户名字
                            SPUtils.getInstance().put(Constant.CARD, jsonObject.optJSONObject("data").optString("card"),true);//认证
                            SPUtils.getInstance().put(Constant.FACE, jsonObject.optJSONObject("data").optString("face"),true);//头像地址(无需拼接)
                            SPUtils.getInstance().put(Constant.TOKEN, jsonObject.optJSONObject("data").optString("token"),true);//token
                            SPUtils.getInstance().put(Constant.ISACCOUNT, jsonObject.optJSONObject("data").optString("is_account"),true);//是否认证
                            SPUtils.getInstance().put(Constant.ALIAS, jsonObject.optJSONObject("data").optString("alias"),true);//别名
                            SPUtils.getInstance().put(Constant.STATE, jsonObject.optJSONObject("data").optString("state"),true);//登录状态
                            SPUtils.getInstance().put(Constant.JOINTEL, jsonObject.optJSONObject("data").optString("join_tel"),true);//加盟电话
                            SPUtils.getInstance().put(Constant.SERVICETEL, jsonObject.optJSONObject("data").optString("service_tel"),true);//客服电话
                            SPUtils.getInstance().put(Constant.SAFETYURL, jsonObject.optJSONObject("data").optString("safety_url"),true);//网页
                            SPUtils.getInstance().put(Constant.REMARK, jsonObject.optJSONObject("data").optString("remark"),true);//remark
                            SPUtils.getInstance().put(Constant.ISPARTNER, jsonObject.optJSONObject("data").optInt("is_partner"),true);//is_partner
                            SPUtils.getInstance().put(Constant.ISDEPOSIT, jsonObject.optJSONObject("data").optString("is_deposit"),true);//是否有押金
                            SPUtils.getInstance().put(Constant.ISBANKCARD, jsonObject.optJSONObject("data").optString("is_bank_card"),true);//是否绑定银行卡
                            SPUtils.getInstance().put("member_token", jsonObject.optJSONObject("data").optString("member_token"),true);
                            MyApplication.initJiGuangUser(jsonObject.optJSONObject("data").optString("alias"),MainActivity.this);//绑定推送别名
                        }else if (Constant.BACKLOGIN.equals(jsonObject.optString("status"))) {
                            SPUtils.getInstance().clear();
                            JumpKillActivitys(LoginActivity.class);
                        }

                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 6) {
            startLocation();
        }
    }

    //获取未读消息
    public void getUnreadNumber() {
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            JsonObject areaJsonobject = new JsonObject();
            areaJsonobject.addProperty("member_id", SPUtils.getInstance().getString(Constant.MEMBER_ID));
            XHttpRequest.getInstance().postRequests(Url.UNREADNUMBER, areaJsonobject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) throws JSONException{
                    if (!StringUtils.isEmpty(result)) {
                            if (isFinishing()) {
                                return;
                            }
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString(Constant.STATUS))) {
                                    int msgNumber = jsonObject.optJSONObject("data").optInt("unread_number");
                                    if (msgNumber > 0) {
                                        BadgerUtils.addBadger(MainActivity.this, jsonObject.optJSONObject("data").optInt("unread_number"));
                                        unreadMsg.setVisibility(View.VISIBLE);//显示角标
                                    } else {
                                        BadgerUtils.removeCount(MainActivity.this);//移除角标
                                        unreadMsg.setVisibility(View.GONE);
                                    }
                                }
                            }

                    }
                }

                @Override
                public void failedRequest(String result) {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });

        }
    }

    @Override
    public void initData() {
    }

    //一进来检测当前车辆信息,下面图片改变
    private void checkUsingFirst(final int where) {
        JsonObject check = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            check.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        XHttpRequest.getInstance().postRequests(Url.CHECKUSEING, check.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString(Constant.STATUS))) {
                                if (Constant.ONE.equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {//运行中
                                    isOpen = true;
                                    scan.setImageResource(R.drawable.ridings);
                                } else if (Constant.TWOS.equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {//车辆暂停
                                    isOpen = true;
                                    scan.setImageResource(R.drawable.ridings);
                                } else if (Constant.THREE.equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {//未付款
                                    scan.setImageResource(R.drawable.payment);
                                }
                            } else {
                                if (Constant.ONES == where) {
                                    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putDouble("lat", mTargetInfoModel.getLatitude());
                                    bundle.putDouble("lng", mTargetInfoModel.getLongitude());
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    /**
     * 点击扫码借车后检测当前车辆状态信息
     **/
    private void checkUsing(final int where) {
        JsonObject check = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            check.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        XHttpRequest.getInstance().postRequests(Url.CHECKUSEING, check.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString(Constant.STATUS))) {
                                if (Constant.ONE.equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {//状态1跳转骑行中
                                    isOpen = true;
                                    scan.setImageResource(R.drawable.ridings);
                                    Intent intent = new Intent(MainActivity.this, RidingActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("vehicle_id", jsonObject.optJSONObject("data").optString("vehicle_id"));
                                    bundle.putString("order_id", jsonObject.optJSONObject("data").optString("order_id"));
                                    bundle.putString("number", jsonObject.optJSONObject("data").optString("number"));
                                    bundle.putString("vehicle_status", jsonObject.optJSONObject("data").optString("vehicle_status"));
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                } else if (Constant.TWOS.equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {//状态2也跳转骑行中,不过状态是车辆暂停
                                    isOpen = true;
                                    scan.setImageResource(R.drawable.ridings);
                                    Intent intent = new Intent(MainActivity.this, RidingActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("vehicle_id", jsonObject.optJSONObject("data").optString("vehicle_id"));
                                    bundle.putString("order_id", jsonObject.optJSONObject("data").optString("order_id"));
                                    bundle.putString("number", jsonObject.optJSONObject("data").optString("number"));
                                    bundle.putString("vehicle_status", jsonObject.optJSONObject("data").optString("vehicle_status"));
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                } else if (Constant.THREE.equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {//状态3是未付款跳转行程结算界面
                                    scan.setImageResource(R.drawable.payment);
                                    Intent intent = new Intent(MainActivity.this, RidingPriceActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("time", jsonObject.optJSONObject("data").optString("run_time"));
                                    bundle.putString("id", jsonObject.optJSONObject("data").optString("order_id"));
                                    bundle.putString("number", jsonObject.optJSONObject("data").optString("number"));
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            } else {
                                if (1 == where) {//跳扫码界面
                                    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putDouble("lat", mTargetInfoModel.getLatitude());
                                    bundle.putDouble("lng", mTargetInfoModel.getLongitude());
                                    bundle.putString("camflag", "1");
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void checkBabyUsingFirst(final int where) {
        JsonObject check = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            check.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        XHttpRequest.getInstance().postRequests(Url.BABYCHECKUSEING, check.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString(Constant.STATUS))) {
                                if (Constant.ONE.equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {//运行中
                                    isOpen = true;
                                    walkBabyScan.setImageResource(R.drawable.ridings);
                                }
                            } else {
                                if (where == 2) {
                                    Intent intent = new Intent(MainActivity.this, BabyCaptureActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putDouble("lat", mTargetInfoModel.getLatitude());
                                    bundle.putDouble("lng", mTargetInfoModel.getLongitude());
                                    intent.putExtras(bundle);
                                    startActivity(intent);

                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void checkBabyUsing(final int where) {
        JsonObject check = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            check.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        XHttpRequest.getInstance().postRequests(Url.BABYCHECKUSEING, check.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString(Constant.STATUS))) {
                                if (Constant.ONE.equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {//状态1跳转用车提醒
                                    isOpen = true;
                                    walkBabyScan.setImageResource(R.drawable.ridings);
                                    Intent intent = new Intent(MainActivity.this, WalkBabyTipsActivity.class);
                                    startActivity(intent);
                                }  else if (Constant.TWOS.equals(jsonObject.optJSONObject("data").optString("vehicle_status"))) {//状态2跳转计费
                                    isOpen = true;
                                    walkBabyScan.setImageResource(R.drawable.ridings);
                                    Intent intent = new Intent(MainActivity.this, WalkBabyRidingActivity.class);
                                    startActivity(intent);
                                } else {
                                    Intent intent = new Intent(MainActivity.this, BabyCaptureActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putDouble("lat", mTargetInfoModel.getLatitude());
                                    bundle.putDouble("lng", mTargetInfoModel.getLongitude());
                                    intent.putExtras(bundle);
                                    startActivity(intent);

                                }
                            } else {
                                if (2 == where) {//跳扫码界面
                                    Intent intent = new Intent(MainActivity.this, BabyCaptureActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putDouble("lat", mTargetInfoModel.getLatitude());
                                    bundle.putDouble("lng", mTargetInfoModel.getLongitude());
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //自定义清除地图的覆盖物
    private void mapClear() {
        if (carBitDList.size() > 0) {
            for (BitmapDescriptor bitmapDescriptor : carBitDList) {
                bitmapDescriptor.recycle();
            }
            carBitDList.clear();
        }
        if (stationMarkersList.size() > 0) {
            for (Overlay overlay : stationMarkersList) {
                overlay.remove();
            }
            stationMarkersList.clear();
        }
        if (carMarkersList.size() > 0) {
            for (Overlay overlay : carMarkersList) {
                overlay.remove();
            }
            carMarkersList.clear();
        }
        if (stationOverlaysList.size() > 0) {
            for (Overlay overlay : stationOverlaysList) {
                overlay.remove();
            }
            stationOverlaysList.clear();
        }
        if (stationWalkBabyOverlaysList.size() > 0) {
            for (Overlay overlay : stationWalkBabyOverlaysList) {
                overlay.remove();
            }
            stationWalkBabyOverlaysList.clear();
        }
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OpenOrClose openOrClose) {
        if (openOrClose.isOpen) {
            scan.setImageResource(R.drawable.ridings);
        } else {
            scan.setImageResource(R.drawable.scan);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OpenOrCloseBaby openOrCloseBaby) {
        if (openOrCloseBaby.isOpen) {
            walkBabyScan.setImageResource(R.drawable.ridings);
        } else {
            walkBabyScan.setImageResource(R.drawable.scan);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUnReadNumberEvent(String str) {
        if (TextUtils.equals(str, EventBusConstants.REFRESH_UNREAD_MSG)) {
            getUnreadNumber();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String str) {
        if (TextUtils.equals(str, EventBusConstants.PAYMENT_STATUS)) {
            scan.setImageResource(R.drawable.payment);
        }
    }

    //推送踢人下线
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginOutEvent(String str) {
        if (TextUtils.equals(str, EventBusConstants.LOGIN_OUT)) {
            ToastUtil.showToast(getString(R.string.login_out_txt));
            SPUtils.getInstance().clear();
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        }
    }

    //骑行中返回强制是站点模式
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRfreshLocationBackEvent(String str) {
        if (TextUtils.equals(str, EventBusConstants.RFRESHBACKLOCATION)) {
            networkEleMode.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_left_choose_bg));
            eleCarMode.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_right_unchoose_bg));
            networkEleMode.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
            eleCarMode.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
            Constant.TYPE = 1;
            BaiDuUtils.locationTarget(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mMap, 18f);
            Constant.latLng = new LatLng(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude());
            mapClear();
            getStation(Constant.latLng);

        }
    }

    //付款成功返回主页强制是站点模式并刷新当前定位
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccessRfreshLocationEvent(String str) {
        if (TextUtils.equals(str, EventBusConstants.PAYSUCCESSRFRESHLOCATION)) {
            networkEleMode.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_left_choose_bg));
            eleCarMode.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_right_unchoose_bg));
            networkEleMode.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
            eleCarMode.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
            Constant.TYPE = 1;
            BaiDuUtils.locationTarget(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude(), mMap, 18f);
            Constant.latLng = new LatLng(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude());
            mapClear();
            getStation(Constant.latLng);
        }
    }

    //遛娃结束后回到主页
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WalkBabyMode walkBabyMode) {
        Constant.MODE = 2;
        carmodeBtn.setBackgroundResource(R.drawable.carmodeleft_shape);
        walkbabyBtn.setBackgroundResource(R.drawable.walkbabyright_shape);
        carmodeBtn.setTextColor(getResources().getColor(R.color.gray_FF959595));
        walkbabyBtn.setTextColor(getResources().getColor(R.color.black));
        carRightmodeLayout.setVisibility(View.GONE);//隐藏右边的站点和车辆模式
        mainCarModeBottom.setVisibility(View.GONE);//共享电动车模式底部显示定位，客服
        mainWalkbabybottom.setVisibility(View.VISIBLE);//遛娃手推车模式底部只显示扫码
        loadWalkBabyMarkers();
        getWalkBabyCar(Constant.latLng);

    }

    //站点模式搜索线路
    private void bikePointsearch(final double lat, final double lng, final String path, final String vehicleNumber, final String name) {
        showLoadingDialog("请稍候...");
        if (stepLine != null) {
            stepLine.remove();
        }
        if (routePlanning == null) {
            routePlanning = new RoutePlanning();
        }
        routePlanning.setByLocation(new LatLng(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude()), new LatLng(lat, lng));
        routePlanning.init();
        routePlanning.setOnWalkingCallBack(new RoutePlanning.OnWalkingCallBack() {
            @Override
            public void onWalkingCallBack(final WalkingRouteResult result) {
                dismissLoadingDialog();
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    ToastUtil.showToast("路径规划失败");
                    return;
                }
                if (result.getRouteLines() == null || result.getRouteLines().size() == 0) {
                    ToastUtil.showToast("未找到目标点的路径");
                    return;
                }
                List<WalkingRouteLine> routeLines = result.getRouteLines();
                List<WalkingRouteLine.WalkingStep> walkingSteps = routeLines.get(0).getAllStep();
                if (walkingSteps == null || walkingSteps.size() == 0) {
                    ToastUtil.showToast("未找到目标点的路径");
                    return;
                }
                final List<LatLng> stepPoint = new ArrayList<>();
                if (walkingSteps.size() > 2) {
                    for (int i = 0; i < walkingSteps.size(); i++) {
                        if (i < walkingSteps.size()) {
                            if (walkingSteps.get(i).getWayPoints().size() > 2) {
                                stepPoint.addAll(walkingSteps.get(i).getWayPoints());
                            }
                        }
                    }
                    if (stepLine != null) {
                        stepLine.remove();
                    }
                    if (stepPoint.size() > 2) {
                        stepLine = BaiDuUtils.drawliness(mMap, stepPoint);
                    }
                }
            }
        });
        routePlanning.startSearch(1, -1);
    }

    //车辆模式规划路线
    private void Bikesearch(final double lat, final double lng, final String vehicle_number, final String power, String journey) {
        showLoadingDialog("请稍候...");
        if (routePlanning == null) {
            routePlanning = new RoutePlanning();
        }
        if (stepLine != null) {
            stepLine.remove();
        }
        routePlanning.setByLocation(new LatLng(mTargetInfoModel.getLatitude(), mTargetInfoModel.getLongitude()), new LatLng(lat, lng));
        routePlanning.init();
        routePlanning.setOnWalkingCallBack(new RoutePlanning.OnWalkingCallBack() {
            @Override
            public void onWalkingCallBack(final WalkingRouteResult result) {
                dismissLoadingDialog();
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    ToastUtil.showToast("路径规划失败");
                    return;
                }
                if (result.getRouteLines() == null || result.getRouteLines().size() == 0) {
                    ToastUtil.showToast("未找到目标点的路径");
                    return;
                }
                List<WalkingRouteLine> routeLines = result.getRouteLines();
                List<WalkingRouteLine.WalkingStep> walkingSteps = routeLines.get(0).getAllStep();
                if (walkingSteps == null || walkingSteps.size() == 0) {
                    ToastUtil.showToast("未找到目标点的路径");
                    return;
                }
                final List<LatLng> stepPoint = new ArrayList<>();
                if (walkingSteps.size() > Constant.TWO) {
                    for (int i = 0; i < walkingSteps.size(); i++) {
                        if (i < walkingSteps.size()) {
                            if (walkingSteps.get(i).getWayPoints().size() > Constant.TWO) {
                                stepPoint.addAll(walkingSteps.get(i).getWayPoints());
                            }
                        }
                    }
                    if (stepLine != null) {
                        stepLine.remove();
                    }
                    if (stepPoint.size() > 2) {
                        stepLine = BaiDuUtils.drawliness(mMap, stepPoint);
                    }
                }
            }
        });
        routePlanning.startSearch(1, -1);
    }

    // 显示上方车辆信息
    @SuppressLint("SetTextI18n")
    private void showBikePointInfo(double showdistance, final String path, final String vehicleNumber, String name) {
        if (Constant.ZERO.equals(vehicleNumber)) {
            parentBikePoint.setVisibility(View.VISIBLE);
            seeBikePoint.setBackgroundResource(R.drawable.gray_shape);
            seeBikePoint.setEnabled(true);
            address.setText(path);
            showNameAddress.setText(name);
            distance.setText(MyUtil.formatBy2Scale(showdistance, 0) + "");
            min.setText(1 + "");
            bikeNumber.setText(vehicleNumber + "");
            seeBikePoint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    parentBikePoint.setVisibility(View.GONE);
                    if (stepLine != null) {
                        stepLine.remove();
                    }
                    ToastUtil.showToast("该站点没有车辆");
                }
            });
        } else {
            parentBikePoint.setVisibility(View.VISIBLE);
            seeBikePoint.setBackgroundResource(R.drawable.yellow_gradient);
            seeBikePoint.setEnabled(true);
            address.setText(path);
            showNameAddress.setText(name);
            distance.setText(MyUtil.formatBy2Scale(showdistance, 0) + "");
            min.setText(1 + "");
            bikeNumber.setText(vehicleNumber + "");
            seeBikePoint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    parentBikePoint.setVisibility(View.GONE);
                    if (stepLine != null) {
                        stepLine.remove();
                    }
                    if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                        JumpActivitys(LoginActivity.class);
                    } else {
                        Intent intent = new Intent(MainActivity.this, BikePointListActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("fixed_id", mFixedId);
                        bundle.putString("address", mTempAddress);
                        bundle.putDouble("lat", mTargetInfoModel.getLatitude());
                        bundle.putDouble("lng", mTargetInfoModel.getLongitude());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }
            });
        }

    }

    @SuppressLint("SetTextI18n")
    private void showBikePointInfos(double distances, final String path, final String vehicleNumber, double showmin, String names) {
        if (Constant.ZERO.equals(vehicleNumber)) {
            parentBikePoint.setVisibility(View.VISIBLE);
            seeBikePoint.setBackgroundResource(R.drawable.gray_shape);
            seeBikePoint.setEnabled(true);
            address.setText(path);
            distance.setText(MyUtil.formatBy2Scale(distances, 0) + "");
            min.setText(MyUtil.formatBy2Scale(showmin, 0) + "");
            bikeNumber.setText(vehicleNumber + "");
            showNameAddress.setText(names);
            seeBikePoint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    parentBikePoint.setVisibility(View.GONE);
                    if (stepLine != null) {
                        stepLine.remove();
                    }
                    ToastUtil.showToast("该站点没有车辆");
                }
            });
        } else {
            parentBikePoint.setVisibility(View.VISIBLE);
            seeBikePoint.setBackgroundResource(R.drawable.yellow_gradient);
            seeBikePoint.setEnabled(true);
            address.setText(path);
            distance.setText(MyUtil.formatBy2Scale(distances, 0) + "");
            min.setText(MyUtil.formatBy2Scale(showmin, 0) + "");
            bikeNumber.setText(vehicleNumber + "");
            showNameAddress.setText(names);
            seeBikePoint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                        parentBikePoint.setVisibility(View.GONE);
                        if (stepLine != null) {
                            stepLine.remove();
                        }
                    } else {
                        parentBikePoint.setVisibility(View.GONE);
                        if (stepLine != null) {
                            stepLine.remove();
                        }
                        Intent intent = new Intent(MainActivity.this, BikePointListActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("fixed_id", mFixedId);
                        bundle.putString("address", mTempAddress);
                        bundle.putDouble("lat", mTargetInfoModel.getLatitude());
                        bundle.putDouble("lng", mTargetInfoModel.getLongitude());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }
            });
        }
    }

    //查看车辆信息
    @SuppressLint("SetTextI18n")
    private void showBikeInfo(final String vehicleNumber, final String power, final double distance, double minuntes) {
        parentBike.setVisibility(View.VISIBLE);
        openLock.setEnabled(true);
        openLock.setBackgroundResource(R.drawable.yellow_gradient);
        String carVehicleNumber = getString(R.string.order_details_title1) + vehicleNumber + "";
        this.number.setText(carVehicleNumber);
        walkDistance.setText(MyUtil.formatBy2Scale(distance, 0) + "");
        walkMin.setText(MyUtil.formatBy2Scale(minuntes, 0) + "");
        bikePower.setText(power);
    }

    //远程借车跳转立即借车界面
    private void remoteDetection(final String vehicleId, final String numbers) {
        Intent intent = new Intent(MainActivity.this, ScanInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("vehicle_id", vehicleId);
        bundle.putString("isRomote", "2");
        bundle.putString("devicenumber", numbers);
        bundle.putDouble("lat", mTargetInfoModel.getLatitude());
        bundle.putDouble("lng", mTargetInfoModel.getLongitude());
        bundle.putString("vehicle_status", "2");
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void cancelTask() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }

        if (timers != null) {
            timers.cancel();
            timers.purge();
            timers = null;
        }
    }


    private void UpdateApp() {
        XHttpRequest.getInstance().getRequest(Url.BASE_URL + "/api.php/Apply/update/version_code/" + MyUtil.getVersionName() + "/apply_type/1", new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) throws JSONException {
                if (!StringUtils.isEmpty(result)) {
                    JSONObject jsonObject = new JSONObject(result);
                    if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                        String explain=jsonObject.optJSONObject("data").optString("explain");
                        String title=jsonObject.optJSONObject("data").optString("title");
                        final String store_url=jsonObject.optJSONObject("data").optString("store_url");
                        final String isUpdate=jsonObject.optJSONObject("data").optString("is_update");
                        UpdateAppDialog.createStartCarDialog(MainActivity.this, title, explain, isUpdate,new OnAskDialogCallBack() {
                            @Override
                            public void onokey(Dialog dialog) {
                                dialog.dismiss();
                                update(store_url);
                            }

                            @Override
                            public void onCancel(Dialog dialog) {
                                dialog.dismiss();

                            }
                        });
                    }else {

                    }
                }
            }

            @Override
            public void failedRequest(String result) {}
        });
    }

    private DownloadProssDialog downloadProssDialog;
    DownloadService downloadService;
    DownloadService.LocalBinder localBinder;
    private int isException = 0;



    private void update(String apkPath) {
        LogUtils.e("apkpath==" + apkPath);
        if (null == downloadProssDialog) {
            downloadProssDialog = new DownloadProssDialog(this, R.style.RcDialog);
        }
        downloadProssDialog.show();
        downloadProssDialog.setProgress(0, "连接服务器中,请等待...");
        Intent intent = new Intent(this, DownloadService.class);
        intent.setAction(DownloadService.ACTION_UPDATE);
        intent.putExtra(DownloadService.EXTRA_APK_PATH, apkPath);
        startService(intent);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }


    private final ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder binder) {
            downloadService = ((DownloadService.LocalBinder) binder).getService();
            localBinder = (DownloadService.LocalBinder) binder;
            listenProgress();
        }

        public void onServiceDisconnected(ComponentName arg0) {
            downloadService = null;
        }
    };

    boolean flag = true;

    void listenProgress() {
        Observable.interval(100, TimeUnit.MILLISECONDS)
                .takeWhile(new Func1<Long, Boolean>() {
                    @Override
                    public Boolean call(Long aLong) {
                        return localBinder.getProgress() <= 100 && flag;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(final Object aLong) {
                progress = localBinder.getProgress();
                if (progress < 100 && progress >= 0) {
                    if (null != downloadProssDialog) {
                        downloadProssDialog.show();
                        downloadProssDialog.setProgress(progress, "正在下载中...");
                    }
                } else if (progress >= 100) {
                    flag = false;
                    dismissDialog();
                }else if (progress == -100) {
                    dismissDialog();
                    if (isException == 0) {
                        isException++;
                        ToastUtil.showToast(localBinder.getDownloadExceptionInfo());
                    }
                }


            }
        });
    }

    private void dismissDialog() {
        if (null != downloadProssDialog) {
            downloadProssDialog.dismiss();
            localBinder.setDownloadEnd();
            downloadProssDialog = null;
        }
        unbindService(mConnection);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mclicktime < Constant.CLICKTIME) {
                this.finish();
                MyUtil.getInstance().clear();
                Process.killProcess(Process.myPid());
                if (handler != null) {
                    handler.removeCallbacksAndMessages(null);
                }
                cancelTask();
            } else {
                ToastUtil.showToast(getString(R.string.press_exit));
                mclicktime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
